package good.idea.data.utils;

import ognl.DefaultMemberAccess;
import ognl.Ognl;
import ognl.OgnlException;

import java.util.Map;

/**
 * @author chenhuanmou
 * 解析ognl表達式工具類
 */

public class OgnlParser {
	private Map context = null;
	private Object target = null;

	/**
	 * 默認構造函數,與當前class綁定
	 */
	public OgnlParser(){
		context = Ognl.createDefaultContext(this);
		target = this;
	}

	/**
	 * 構造函數，綁定目標class
	 * @param className
	 */
	public OgnlParser(String className){
		try {
			target = Class.forName(className).newInstance();
			context = Ognl.createDefaultContext(target);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 構造函數，綁定目標bean
	 * @param targetBean 綁定bean
	 */
	public OgnlParser(Object targetBean){
		try {
			target = targetBean;
			context = Ognl.createDefaultContext(target);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根據表達式獲取綁定bean的屬性值，如果表達式解析出錯，則會停止代碼執行並拋出異常信息
	 * @param expression 標準的OGNL表達式
	 * @return
	 */
	public Object getValue(String expression) {
		DefaultMemberAccess  aMemberAccess = new DefaultMemberAccess(true);
		Ognl.setMemberAccess(context, aMemberAccess);
		Object val=null;
		try {
			val=Ognl.getValue(expression, context, target);
		} catch (OgnlException e) {
			//System.out.println(expression+"=========="+target);
			//e.printStackTrace();
		}
		return val;
	}
}
